//////////////////////////////////////////////////////////////////////////
#include "GameObject.h"
#include <Box2D/Box2D.h>
#include "Sprite/Sprite.h"
#include "HotSpot/HotSpot.h"
//////////////////////////////////////////////////////////////////////////
extern HGE *hge;
//////////////////////////////////////////////////////////////////////////
GameObject::GameObject()
: m_physBody(NULL)
, m_Sprite(NULL)
{
	
}
//////////////////////////////////////////////////////////////////////////
GameObject::~GameObject()
{
	
}
//////////////////////////////////////////////////////////////////////////
void GameObject::createPhysBody( b2World* world, float density, bool staticBody, bool sleep )
{
	assert(world);
	if(!world)
		return;

	b2BodyDef bodyDef;

	if(staticBody)
		bodyDef.type = b2_staticBody;
	else
		bodyDef.type = b2_dynamicBody;

	bodyDef.position.Set(m_x * PHYS_COORDS_SCALE, m_y * PHYS_COORDS_SCALE);
	bodyDef.angle = m_angle;
	bodyDef.allowSleep = true;
	bodyDef.awake = !sleep;

	m_physBody = world->CreateBody(&bodyDef);
	
	b2PolygonShape shape;
	shape.SetAsBox(static_cast<float>(m_Sprite->getWidth()-2) * PHYS_COORDS_SCALE * 0.5f, 
					static_cast<float>(m_Sprite->getHeight()-2) * PHYS_COORDS_SCALE * 0.5f
				   );

	b2FixtureDef fixtureDef;
	fixtureDef.shape = &shape;
	fixtureDef.density = density;
	fixtureDef.restitution = 0.5;
	
	m_physBody->CreateFixture(&fixtureDef);
}
//////////////////////////////////////////////////////////////////////////
void GameObject::update( float dt )
{
	CompositeObject::update(dt);

	if(m_physBody)
	{
		b2Vec2 pos = m_physBody->GetPosition();
		m_x = pos.x / PHYS_COORDS_SCALE;
		m_y = pos.y / PHYS_COORDS_SCALE;
		setAngle(m_physBody->GetAngle());
	}
}
//////////////////////////////////////////////////////////////////////////
void GameObject::setSprite( const wchar_t* path )
{
	assert(path);
	if(!path)
		return;

	Sprite* sprite = new Sprite();
	addChild(sprite);
	sprite->setTexturePath(path);
	float width = static_cast<float>(sprite->getWidth());
	float height = static_cast<float>(sprite->getHeight());
	sprite->setAnchor(width / 2, height / 2);

	m_Sprite = sprite;

	//setup hotspot
	HotSpot* hotSpot = new HotSpot();
	hotSpot->addPoint(-width/2, -height/2);
	hotSpot->addPoint(width/2, -height/2);
	hotSpot->addPoint(width/2, height/2);
	hotSpot->addPoint(-width/2, height/2);
	addChild(hotSpot);
	m_HotSpot = hotSpot;
}

//////////////////////////////////////////////////////////////////////////
